using System.Collections;
using System.Collections.Generic;
using QFramework;
using UnityEngine;


namespace TowerDefence_QF
{
    public class PathSystem : AbstractSystem
    {
        /// <summary>
        /// 加载器
        /// </summary>
        private ResLoader mResLoader;
        /// <summary>
        /// 地图预制体路径
        /// </summary>
        private const string MAP_PATH = "map";
        /// <summary>
        /// 地图实例
        /// </summary>
        private Transform mMapTransform;
        /// <summary>
        /// 地图预制体
        /// </summary>
        private GameObject mMapPrefab;
        /// <summary>
        /// 方块预制体路径
        /// </summary>
        private const string CUBE_PATH = "map_box";
        /// <summary>
        /// 方块预制体
        /// </summary>
        private GameObject mCubePrefab;
        /// <summary>
        /// 方块对象池
        /// </summary>
        private SimpleObjectPool<GameObject> mCubePool;
        /// <summary>
        /// 使用的方块集合
        /// </summary>
        private List<GameObject>mCubeList;
        /// <summary>
        /// 地图路径的集合
        /// </summary>
        private List<List<Vector3>>mV3List;

        private int mLevelIndex;


        private const string V3_AB_PATH = "MapText";
             
        protected override void OnInit()
        {
            //初始化加载器
            mResLoader=ResLoader.Allocate();
            
            mV3List = new List<List<Vector3>>();
            mCubeList = new List<GameObject>();
            //加载地图预制体
            mMapPrefab = mResLoader.LoadSync<GameObject>(MAP_PATH);

            StringEventSystem.Global.Register(NameData.END_LEVEL, RecycleCube);
            //初始化方块池
            InitCubePool();
            //初始化路径
            Initpath();
        }
        /// <summary>
        /// 卸载时
        /// </summary>
        protected override void OnDeinit()
        {
            base.OnDeinit();
            StringEventSystem.Global.UnRegister(NameData.END_LEVEL, RecycleCube);
            mMapTransform=null;
            mMapPrefab=null;
            mCubePrefab=null;

            mCubeList.Clear();
            mV3List.Clear();
            mCubeList = null;
            mV3List = null;

            mResLoader.Recycle2Cache();
            mResLoader = null;
        }


        /// <summary>
        /// 生成地图
        /// </summary>
        private void GenerateMap()
        {
            mMapTransform =  mMapPrefab.Instantiate().transform;
        }
        /// <summary>
        /// 加载预制体，初始化方块池
        /// </summary>

        private void InitCubePool()
        {
            mCubePrefab = mResLoader.LoadSync<GameObject>(CUBE_PATH);
            
            mCubePool = new SimpleObjectPool<GameObject>(() =>
            {
                if (mMapTransform == null) GenerateMap();

                var go =GameObject.Instantiate(mCubePrefab, mMapTransform);
                go.Show();
                return go;

            }, (go) =>
            {
                go.Hide();
            });
        }
        
        /// <summary>
        /// 加载地图ab包，加载,解析地图文件
        /// </summary>
        private void Initpath()
        {
            //加载ab包
            var ab = mResLoader.LoadSync<AssetBundle>(V3_AB_PATH);
            //加载所有文本文件
            var texts =ab.LoadAllAssets<TextAsset>();
            //自动排序字典
            SortedDictionary<int, string> mtextFile = new SortedDictionary<int, string>();
            //遍历文本资源，截取数字，储存进字典
            foreach (TextAsset textAsset in texts)
            {
                string[] parts = textAsset.name.Split('_');

                if (parts.Length > 1)
                {
                    string numberPart = parts[parts.Length - 1]; // 取最后一部分
                    if (int.TryParse(numberPart, out int number))
                    {
                        mtextFile.Add(number, textAsset.text);
                    }
                }
            }

            // 将值转换为 List<string>
            List<string> pathList = new List<string>(mtextFile.Values);
            //解析文本，获取路径集合
            GetV3List(pathList);
        }

        /// <summary>
        /// 根据索引创建路径
        /// </summary>
        /// <param name="levelIndex"></param>
        public void GeneratePath(int levelIndex)
        {
            if (mMapTransform == null) GenerateMap();

            mLevelIndex = levelIndex;
            //获取路径
            var pathList = mV3List[mLevelIndex];
            //获取第一个点
            Vector3 pos = pathList[0];
            //创建第一个方块
            GameObject cube;
            cube = mCubePool.Allocate();
            cube.LocalPosition(pos);
            cube.Show();
            mCubeList.Add(cube);
            ///根据算法生成路径
            for (int i = 0; i < pathList.Count; i++)
            {
                while (pos.x > pathList[i].x)
                {
                    pos.x--;
                    cube = mCubePool.Allocate();
                    cube.LocalPosition(pos);
                    cube.Show();
                    mCubeList.Add(cube);
                }
                while (pos.x < pathList[i].x)
                {
                    pos.x++;
                    cube = mCubePool.Allocate();
                    cube.LocalPosition(pos);
                    cube.Show();
                    mCubeList.Add(cube);
                }
                while (pos.z < pathList[i].z)
                {
                    pos.z++;
                    cube = mCubePool.Allocate();
                    cube.LocalPosition(pos);
                    cube.Show();
                    mCubeList.Add(cube);
                }
                while (pos.z > pathList[i].z)
                {
                    pos.z--;
                    cube = mCubePool.Allocate();
                    cube.LocalPosition(pos);
                    cube.Show();
                    mCubeList.Add(cube);
                }
            }
        }

        public List<Vector3> GetV3List()
        {
            return mV3List[mLevelIndex];
        }

        /// <summary>
        /// 回收方块
        /// </summary>
        private void RecycleCube()
        {
            foreach (var cube in mCubeList)
            {
                mCubePool.Recycle(cube);
            }
            mCubeList.Clear();
        }
        /// <summary>
        /// 解析文本文件，获取地图坐标
        /// </summary>

        private void GetV3List(List<string>pathList)
        {
            
            foreach(var pathText in pathList)
            {
                string[] posStrings = pathText.TrimEnd('\n').Split('\n');

                string[] posXZ;
                var v3List = new List<Vector3>();
                for (int i = 0; i < posStrings.Length; i++)
                {
                    posXZ = posStrings[i].Split(',');
                    v3List.Add(new Vector3(int.Parse(posXZ[0]), 0, int.Parse(posXZ[1])));
                }
                mV3List.Add(v3List);
            }
           
        }

       
    }
}

